// dom 元素
const container = document.querySelector('.container')
const list = document.querySelector('#list')

/**
 * 解析歌词为对象数组
 * @returns
 */
function parseLrcData() {
  let lines = lrc.split('\n')
  let words = lines.map(line => {
    let [time, text] = line.split(']')
    time = time.substring(1).split(':')
    time = parseFloat(time[0]) * 60 + parseFloat(time[1])
    return { time, text }
  })
  return words
}

let words = parseLrcData()

function createLrcList() {
  const frag = document.createDocumentFragment()
  words.forEach((word, index) => {
    let li = document.createElement('li')
    li.textContent = word.text
    li.index = index
    frag.appendChild(li)
  })
  list.appendChild(frag)
}

createLrcList()

const containerHeight = container.clientHeight
const lineHeight = list.children[0].clientHeight
let currentIndex = 0

/**
 * 查找当前歌词下标
 * @param {number} time 当前播放时间
 * @returns 歌词下标
 */
function findCurrentIndex(time) {
  if (time < words[0].time) return 0
  for (let i = 0; i < words.length - 1; i++) {
    if (time < words[i + 1].time) {
      if (words[i].text === '') {
        return i - 1
      }
      return i
    }
  }
  return words.length - 1
}

/**
 *
 * @param {number} index
 */
function setCurrentLyric(index) {
  if (currentIndex === index) {
    return
  }
  // 设置歌词列表偏移量
  list.style.transform = `translateY(-${
    index * lineHeight - containerHeight / 2
  }px)`

  // 设置当前歌词样式
  let active = list.querySelector('.active')
  if (active) {
    active.classList.remove('active')
  }
  list.children[index].classList.add('active')
  currentIndex = index
}

function setOffset(time) {
  const index = findCurrentIndex(time)
  setCurrentLyric(index)
}

document.querySelector('#music').addEventListener('timeupdate', function (e) {
  let currentTime = e.target.currentTime
  setOffset(currentTime)
})
